package timbap.visualizer.coreplugins;

import processing.core.PApplet;
import timbap.visualizer.api.model.RecordItem;
import timbap.visualizer.api.model.TimeCode;
import timbap.visualizer.api.plugin.container.AbstractTransitionModeController;
import timbap.visualizer.api.plugin.container.PluginSwitchCommand;

public class FlippingDeselectingModeControl extends AbstractTransitionModeController {

	private static final int FLIPPING_ACCELERATION_FACTOR = 5;
	private static final int RECORD_ITEMS_FADE_IN_ACCELERATION_FACTOR = 10;
    private static final String NO_FILE_URI_STRING = "file://";
    private static final String STOP_COMMAND_ADDRESS_PATTERN = "/loadfile";

    private RecordItem selectedRecordItem;

    @Override
    public void activate() {
        super.activate();
        selectedRecordItem = getContext().getRecordItemManager().getSelectedRecordItem();
    }

    public void publishPluginSwitchCommand(PluginSwitchCommand pPluginSwitchCommand) {
        super.publishPluginSwitchCommand(pPluginSwitchCommand);
        if (pPluginSwitchCommand.equals(PluginSwitchCommand.NEXT)) {
            sendStopCommand();
        }
    }

    public void sendStopCommand() {
        getContext().getMessagingManager().sendStringMessage(
                STOP_COMMAND_ADDRESS_PATTERN, NO_FILE_URI_STRING);
        getContext().getRecordItemManager().getSelectedRecordItem().setPlaying(false);
    }

    @Override
    public void timeCodeUpdated(TimeCode pTimeCode) {
        super.timeCodeUpdated(pTimeCode);

        float tElapsedDeselectionTimeFraction = getKeepAliveExpirationAsFractional();

        selectedRecordItem.getTransformation().setXTranslation(0);
        selectedRecordItem.getTransformation().setYTranslation(0);
        selectedRecordItem.getTransformation().setAlphaValue(1.0f);

        float tXRotation = PApplet.map(
        		PApplet.pow(tElapsedDeselectionTimeFraction,
                            FLIPPING_ACCELERATION_FACTOR),
        		0, 1, 0, 2.5f * PApplet.PI);
        selectedRecordItem.getTransformation().setXRotation(tXRotation);
        
        for (RecordItem tRecordItem : getContext().getRecordItemManager().getRecordItems()) {
        	if (!tRecordItem.isSelected()) {
        		float tAlphaValue = PApplet.pow(tElapsedDeselectionTimeFraction,
                                                RECORD_ITEMS_FADE_IN_ACCELERATION_FACTOR);
        		tRecordItem.getTransformation().setAlphaValue(tAlphaValue);
        	}
        }
        
    }


}
